<script setup lang="ts">
import { NLayout, NLayoutSider, NMenu, NCard } from 'naive-ui'
import { useComponentStore } from '@/stores/modules/components'
import { storeToRefs } from 'pinia'
import { useRouter, useRoute, onBeforeRouteUpdate } from 'vue-router'
import { onMounted } from 'vue'

const router = useRouter()
const route = useRoute()
const componentStore = useComponentStore()
const { currentComponentInstance, menuItems } = storeToRefs(componentStore)

const handleComponentChange = (key: string) => {
  componentStore.setCurrentComponent(key)
  router.push(`/practice/${key}`)
}

// 从路由参数同步组件状态
const syncComponentFromRoute = () => {
  const component = route.path.split('/').pop()
  if (component && component in componentStore.componentMap) {
    componentStore.setCurrentComponent(component)
  }
}

// 监听路由变化
onBeforeRouteUpdate((to) => {
  const component = to.path.split('/').pop()
  if (component && component in componentStore.componentMap) {
    componentStore.setCurrentComponent(component)
  }
})

// 初始化时同步
onMounted(() => {
  syncComponentFromRoute()
})
</script>

<template>
  <NLayout has-sider>
    <!-- 侧边栏 -->
    <NLayoutSider
      bordered
      collapse-mode="width"
      :collapsed-width="64"
      :width="240"
      :native-scrollbar="false"
      class="h-screen"
    >
      <NMenu
        :value="componentStore.currentComponent"
        :options="menuItems"
        @update:value="handleComponentChange"
      />
    </NLayoutSider>

    <!-- 主内容区 -->
    <NLayout class="p-8">
      <NCard class="shadow-sm">
        <component :is="currentComponentInstance" />
      </NCard>
    </NLayout>
  </NLayout>
</template>

<style scoped>
:deep(.n-menu) {
  height: 100%;
}

:deep(.n-menu-item) {
  height: 50px;
  font-size: 14px;
}

:deep(.n-menu-item-content) {
  padding: 0 20px;
}

:deep(.n-menu-item-content__icon) {
  margin-right: 12px;
}

:deep(.n-menu-item-content--selected) {
  background-color: #f0f7ff;
  color: #2080f0;
}

:deep(.n-menu-item:hover) {
  background-color: #f6f6f6;
}
</style>
